package com.south.base.test.arithmetic;

import org.junit.Assert;
import org.junit.Test;

/**
 * 罗马数字包含以下七种字符: I， V， X， L，C，D 和 M。
 * <p>
 * 字符          数值
 * I             1
 * V             5
 * X             10
 * L             50
 * C             100
 * D             500
 * M             1000
 *
 * @author Administrator
 * @date 2020/5/27 9:27
 */
public class Roman {
    @Test
    public void test() {
        Assert.assertEquals(3, romanToInt("III"));
        Assert.assertEquals(4, romanToInt("IV"));
        Assert.assertEquals(9, romanToInt("IX"));
        Assert.assertEquals(58, romanToInt("LVIII"));
        Assert.assertEquals(1994, romanToInt("MCMXCIV"));
    }

    /**
     * 罗马数字转整数
     *
     * @param s
     * @return
     */
    public int romanToInt(String s) {
        int last = Integer.MAX_VALUE, sum = 0;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int index = find(c);
            sum = index > last ? (sum + index - (last * 2)) : sum + index;
            last = index;
        }
        return sum;
    }

    public int find(char i) {
        switch (i) {
            case 'I':
                return 1;
            case 'V':
                return 5;
            case 'X':
                return 10;
            case 'L':
                return 50;
            case 'C':
                return 100;
            case 'D':
                return 500;
            case 'M':
                return 1000;
            default:
                return 0;
        }

    }

    @Test
    public void test2() {
        Assert.assertEquals(intToRoman(3), "III");
        Assert.assertEquals(intToRoman(4), "IV");
        Assert.assertEquals(intToRoman(9), "IX");
        Assert.assertEquals(intToRoman(58), "LVIII");
        Assert.assertEquals(intToRoman(1994), "MCMXCIV");
    }

    /**
     * 整数转罗马数字
     *
     * @param num
     * @return
     */
    public String intToRoman(int num) {
        char[] romans = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
        int[] nums = {1, 5, 10, 50, 100, 500, 1000};
        int[] indexes = {0, 2, 4};
        StringBuilder sb = new StringBuilder();
        for (int i = nums.length - 1; i >= 0; ) {
            int tmp = 0;
            if (num >= nums[i]) {
                num -= nums[i];
                sb.append(romans[i]);
            } else {
                for (int j = indexes.length - 1; j >= 0; j--) {
                    if (i > indexes[j]) {
                        tmp = nums[i] - nums[indexes[j]];
                        if (num >= tmp) {
                            num -= tmp;
                            sb.append(romans[indexes[j]]).append(romans[i]);
                        }
                        break;
                    }
                }
            }
            if (num < tmp) {
                i--;
            }
            if (num == 0) {
                break;
            }
        }
        return sb.toString();
    }
}
